﻿#include "FansMonitor.h"
#include "ui_FansMonitor.h"

#include <QDebug>

//预处理
#pragma execution_character_set("utf-8")

//风扇状态
int FansMonitor::FANS_STATUS = 0;
//继电器状态
int FansMonitor::ELECTRIC_RELAY_STATUS = 0;

/**
 *1.创建QTcpServer对象
  2.启动服务器（监听）调用成员方法listen（QHostAddress::Any, 端口号）
  3.当有客户端链接时候会发送newConnection信号，触发槽函数接受链接（得到一个与客户端通信的套接字QTcpSocket）
  4.QTcpsocket发送数据用成员方法write，
  5.读数据当客户端有数据来，QTcpSocket对象就会发送readyRead信号，关联槽函数读取数据
 */
FansMonitor::FansMonitor(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::FansMonitor) {
    ui->setupUi(this);
    //窗口大小固定为UI文件中的默认值
    this->setFixedSize(this->geometry().size());
    //赋初值
    isOpen = false;
    //客户端
    client = new QTcpSocket();
    //服务端
    server = new QTcpServer();
    //查询定时器
    queryTimer = new QTimer();
    //间隔500ms
    queryTimer->setInterval(TIMER_INTERVAL);
    //启动
    queryTimer->start();
    //检查连接的定时器
    checkLinkTimer = new QTimer();
    //间隔500ms
    checkLinkTimer->setInterval(RECONNECTION_INTERVAL);
    //启动
    checkLinkTimer->start();
    //显示ip
    ui->ip_label->setText(FIXED_IP);
    //显示端口号
    ui->port_label->setText(QString::number(FIXED_PORT, 10));
    //建立连接：创建通道，服务器不一定就绪
    client->connectToHost(QHostAddress(FIXED_IP), FIXED_PORT);
    //是否打开
    isOpen = client->isOpen();
    if(isOpen) {
        ui->status_label->setText("Server connection succeeded");
        qDebug() << "连接服务器成功";
    } else {
        ui->status_label->setText("Server connection failed");
        qDebug() << "连接服务器失败";
    }

    //监听服务是否成功连接
    connect(client, &QTcpSocket::connected, this, [ = ]() {
        ui->status_label->setText("Server connection succeeded");
    });

    //监听服务是否断开连接
    connect(client, &QTcpSocket::disconnected, this, [ = ]() {
        ui->status_label->setText("Server disconnected");
        isOpen = false;
    });

    //风扇
    connect(ui->fans_btn, &QPushButton::clicked, [this] {
        //判断是可写操作，isValid表示准备好读写
        if(!client->isValid())
            return;
        if(FANS_STATUS == 0) {
            FANS_STATUS = 1;
        } else {
            FANS_STATUS = 0;
        }
        QByteArray mes = packageMessage();
        client->write(mes);
    });

    //继电器
    connect(ui->relay_btn, &QPushButton::clicked, [this] {
        //isValid表示准备好读写
        if(!client->isValid())
            return;
        if(ELECTRIC_RELAY_STATUS == 0) {
            ELECTRIC_RELAY_STATUS = 1;
        } else {
            ELECTRIC_RELAY_STATUS = 0;
        }
        QByteArray mes = packageMessage();
        client->write(mes);
    });

    //定时查询数据
    connect(queryTimer, &QTimer::timeout, [ = ]() {
        // 接收服务器发送的数据
        QByteArray recvMsg = client->readAll();
        if(recvMsg.isEmpty())
            return;
        qDebug() << "Server sends messages:" + recvMsg;
        //声明目标字符串
        QString readMes = nullptr;
        for(int i = 0; i < recvMsg.size(); i++) {
            readMes += QString("%1").arg((quint8)recvMsg.at(i), 2, 10);
            if(i != recvMsg.length()) {
                readMes += ",";
            }
        }
        QStringList mesList = readMes.split(",");
        int fans_status = mesList.at(1).toInt();
        int relay_status = mesList.at(2).toInt();
        FANS_STATUS = fans_status;
        if(FANS_STATUS == 0) {
            ui->fans_btn->setText("开启");
            ui->fan_label->setText("OFF");
        } else {
            ui->fans_btn->setText("关闭");
            ui->fan_label->setText("ON");
        }
        ELECTRIC_RELAY_STATUS = relay_status;
        if(ELECTRIC_RELAY_STATUS == 0) {
            ui->relay_btn->setText("开启");
            ui->relay_label->setText("OFF");
        } else {
            ui->relay_btn->setText("关闭");
            ui->relay_label->setText("ON");
        }
        //监控赋值
        ui->temperature_line->setText(QString::number(mesList.at(3).toInt()));
        ui->humidity_line->setText(QString::number(mesList.at(4).toInt()));
        ui->motor_temp_line->setText(QString::number(mesList.at(5).toInt()));
        short motor_speed = mesList.at(6).toInt() << 8 | mesList.at(7).toInt();
        ui->motor_speed_line->setText(QString::number(motor_speed, 10));
    });

    //定时检查连接
    connect(checkLinkTimer, &QTimer::timeout, [ = ]() {
        qDebug() << "Checking server connection";
        client->connectToHost(QHostAddress(FIXED_IP), FIXED_PORT);
        isOpen = client->isOpen();
    });
}

FansMonitor::~FansMonitor() {
    delete ui;
}

QByteArray FansMonitor::packageMessage() {
    // 声明字节数组
    QByteArray data;
    // 报文长度
    data.resize(4);
    data[0] = (qint8)0x5a;
    data[1] = (qint8)FANS_STATUS;
    data[2] = (qint8)ELECTRIC_RELAY_STATUS;
    data[3] = (qint8)0xa5;
    return data;
}
